const Mock = require('mockjs')

let AppPackages = []
const appNames = ['movie-tool', 'movie-tool-update', 'ffplayer', 'ffplayer-update']
for (let i = 0; i < 33; ++i) {
  AppPackages.push({
    id: i + 1,
    appName: appNames[i % appNames.length],
    packageType: i % 2 === 0 ? 'Windows' : 'Andorid',
    productType: i % 2 === 1 ? 'Lewin' : 'RH',
    versionName: '1.0.' + i,
    versionCode: i,
    latest: i % 2,
    uploadTime: Mock.Random.datetime()
  })
}

function list(page, limit) {
  limit = Math.max(1, Math.min(parseInt(limit), 50))
  page = Math.max(parseInt(page), 1)
  let mocks = AppPackages.filter(item => {
    return true
  })
  const total = mocks.length
  mocks = mocks.filter((u, index) => index < limit * page && index >= limit * (page - 1))
  return { success: true, data: { total: total, records: mocks }}
}

function save(item) {
  const r = JSON.parse(JSON.stringify(item))
  r.id = AppPackages[AppPackages.length - 1].id + 1
  AppPackages.push(r)
  return r.id
}

function find(id) {
  id = id ? parseInt(id) : null
  for (let i = 0; i < AppPackages.length; ++i) {
    if (AppPackages[i].id === id) {
      const d = AppPackages[i]
      return { ...d }
    }
  }
  return null
}

function setLatest(id) {
  id = id ? parseInt(id) : null
  for (let i = 0; i < AppPackages.length; ++i) {
    if (AppPackages[i].id === id) {
      AppPackages[i].latest = 1
    }
  }
}

function remove(id) {
  id = id ? parseInt(id) : null
  AppPackages = AppPackages.filter(item => item.id !== id)
}

module.exports = { list, save, find, setLatest, remove }
